package com.helloworld.upload;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cfw.exception.BizException;
import com.helloworld.upload.domain.CellInfo;
import com.helloworld.upload.domain.ColumnInfo;
import com.helloworld.upload.domain.UploadInfo;
import com.helloworld.upload.util.ExcelUtil;
import com.helloworld.upload.util.ValidateUtil;

public class Validate {
	private static final Logger logger = LoggerFactory.getLogger(Validate.class);
	
	public static Map<Integer, List<CellInfo>> validateExcel(UploadInfo info, String fileName) throws Exception {
		Map<Integer, List<CellInfo>> rowInfos = new HashMap<Integer, List<CellInfo>>();
		FileInputStream stream = null;
		XSSFExcelExtractor extractor = null;
		
		try {
			stream = ExcelUtil.getFileInputStream(fileName);
			XSSFSheet sheet = ExcelUtil.getExcelSheet(stream);
			
			if (sheet == null) { throw new BizException("E00000"); }
			
			XSSFWorkbook book = sheet.getWorkbook();
			
			extractor = new XSSFExcelExtractor(book);
			FormulaEvaluator evaluator = book.getCreationHelper().createFormulaEvaluator();
			
			extractor.setFormulasNotResults(true);
			extractor.setIncludeSheetNames(false);		
			
			for (Row row : sheet) {
				if (row.getRowNum() == 0) { continue; } // 머리글은 통과
	
				List<CellInfo> cellInfos = new ArrayList<CellInfo>();
				List<ColumnInfo> columns = info.getColumns();
				
				for (ColumnInfo column : columns) {
					Cell cell = null; 
					if (column.getSourceColumnIndex() > -1) { cell = row.getCell(column.getSourceColumnIndex()); }
					if (cell != null) { cell = evaluator.evaluateInCell(cell); }
					CellInfo cellInfo = ValidateUtil.validate(column.getValidateRules(), cell, row.getRowNum(), column.getSourceColumnIndex());
					cellInfos.add(cellInfo);
					
	//				logger.debug("*** cellInfo:" + cellInfo);
				}
				
				rowInfos.put(row.getRowNum(), cellInfos);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (extractor != null) { extractor.close(); }
			if (stream != null) { stream.close(); }
		}
		
		return rowInfos;
	}	
	
	public static void applyResultToExcel(Map<Integer, List<CellInfo>> rowInfos, String sourceName, String targetName) throws Exception {
		FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
		
		try {
			inputStream = ExcelUtil.copyGetInputFileStream(sourceName, targetName);
		
			XSSFSheet sheet = ExcelUtil.getExcelSheet(inputStream);
			
			if (sheet == null) { throw new BizException("E00000"); }
	
			ExcelUtil.writeResult(rowInfos, sheet);
			
			inputStream.close();
			
			outputStream = ExcelUtil.getFileOutputStream(targetName);
			
			sheet.getWorkbook().write(outputStream);
			
			outputStream.close();
		} catch (Exception e) {
			throw e;
		} finally {
			if (inputStream != null) { inputStream.close(); }
			if (outputStream != null) { outputStream.close(); }
		}
	}
	
}
